package com.sdses.weather.service;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.sdses.weather.config.exception.BusinessException;
import com.sdses.weather.factory.WeatherApiProvider;
import com.sdses.weather.model.RequestContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class MojiApiProvider implements WeatherApiProvider {

    @Override
    public String getProviderName() {
        return "moji";
    }

    @Override
    public Map<String, String> buildHeaders(RequestContext context) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + context.getAppcode());
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        return headers;
    }

    @Override
    public Map<String, String> buildFormParams(RequestContext context) {
        return cityParams(context);
    }

    @Override
    public String buildUrl(RequestContext context) {
        return context.getUrl();
    }

    @Override
    public void checkResponse(JsonNode responseNode) {
        if (responseNode.has("code") && !"0".equals(responseNode.get("code").asText())) {
            String msg = responseNode.has("msg") ? responseNode.get("msg").asText() : "未知错误";
            throw new BusinessException("墨迹API错误: " + msg);
        }
    }

    private java.util.Map<String, String> cityParams(RequestContext context) {

        java.util.Map<String, String> params = new java.util.HashMap<>();
        params.put("token", context.getToken());
        if (StrUtil.isNotBlank(context.getCityId())) {

            params.put("cityId", context.getCityId());
        } else if (StrUtil.isNotBlank(context.getLat()) && StrUtil.isNotBlank(context.getLon())) {

            params.put("lat", context.getLat());
            params.put("lon", context.getLon());
        }
        return params;
    }

}